<template>
  <div>
    <div id="search">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="菜单名称">
          <el-input placeholder="请输入菜单名" v-model="titleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button type="primary" size="small" @click="addAuth">新增</el-button>
    </div>
    <div id="auth-table">
      <el-table
          ref="tableList"
          :data="tableData"
          style="width: 100%;"
          row-key="id">
        <el-table-column
            prop="title"
            label="菜单名称"
            width="180">
        </el-table-column>
        <el-table-column
            prop="icon"
            label="图标"
            width="180">
          <template slot-scope="scope">
            <i :class="scope.row.icon"></i>
          </template>
        </el-table-column>
        <el-table-column
            prop="permission"
            label="权限标识">
        </el-table-column>
        <el-table-column
            prop="path"
            label="组件路由">
        </el-table-column>
        <el-table-column
            prop="component"
            label="组件名称">
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-popconfirm style="margin-left: 10px" title="确定删除吗？" @confirm="handleDelete(scope.$index, scope.row)">
              <el-button
                  slot="reference"
                  size="mini"
                  type="danger"
                  >删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--添加 编辑权限信息弹窗-->
    <el-dialog :title="title" :visible.sync="addAuthFormVisible" width="40%" @close="handleClear">
      <el-form :model="authForm" ref="authInfo" :rules="authRules" label-width="80px" size="medium"
               label-position="left">
        <el-input v-model="authForm.id" autocomplete="off" v-show="false"></el-input>
        <el-form-item label="上级菜单" prop="pid">
          <el-select v-model="authForm.pid" ref="select" placeholder="请选择" style="width: 100%">
            <el-option key="id" hidden :value="id" :label="label"></el-option>
            <el-tree ref="tree"
                     style="padding: 0px 10px 10px 0px"
                     :data="list"
                     :expand-on-click-node="false"
                     node-key="id"
                     :default-expand-all="true"
                     @node-click="handleCheck"
            >
            </el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单类型" prop="isMenu">
          <el-radio-group v-model="authForm.isMenu">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="authForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="目录图标" prop="icon">
          <!--图标选择器-->
          <e-icon-picker v-model="authForm.icon"/>
        </el-form-item>

        <el-form-item label="权限标识" prop="permission" v-if="authorityshow">
          <el-input v-model="authForm.permission" autocomplete="off" placeholder="按钮权限标识"></el-input>
        </el-form-item>
        <el-form-item label="组件名称" prop="component" v-if="showcom">
          <el-input v-model="authForm.component" autocomplete="off" placeholder="菜单组件名称"></el-input>
        </el-form-item>

        <el-form-item label="组件路径" prop="path" v-if="showcom">
          <el-input v-model="authForm.path" autocomplete="off" placeholder="菜单路径"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAuthInfo">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listToTree} from "@/util/treeUtil";
import instance from "@/request/request";
import {addPermissionApi, deleteOne, getonePermission, search} from "@/request/api";

export default {
  name: "AuthView",
  data() {
    return {
      tableData: [],
      title:"",
      //控制增加修改
      addAuthFormVisible: false,
      authForm:{
        isMenu: 0,
        pid: '',
      },
      label: '',
      id: '',
      authRules:{
        pid: [
          {required: true, message: '请选择父菜单', trigger: 'blur'}
        ],
        isMenu: [
          {required: true, message: '请填写类型', trigger: 'blur'}
        ],
        title: [
          {required: true, message: '请填写名称', trigger: 'blur'}
        ]
      },
      list:[],
      //权限标识显示
      authorityshow:false,
      showcom:false,
      //搜索菜单名称
      titleName:''
    }

  },
  methods: {
    //搜索
    search(){
      if(this.titleName){
        search(this.titleName).then(res=>{
          if (res.code==200){
            this.tableData=[res.data]
          }
        }).catch(erro=>{
          this.$message.error("请求失败！！")
        })
      }
      this.toTree()
    },
    handleClear(){
      this.authForm = {
        isMenu: 0,
        pid: '',
      }
      this.$refs.authInfo.clearValidate()
    },
    //选择
    handleCheck(val){
      this.label = val.label
      this.id = val.id
      this.authForm.pid = val.id
      // 选择完毕关闭 下拉选
      this.$refs.select.blur()
    },
    //确定
    addAuthInfo(){
      this.$refs.authInfo.validate(valid => {
        if (!valid) {
          this.$message.warning("请填写完整的信息")
          return
        }
        // 发送异步请求 添加菜单信息
        addPermissionApi(this.authForm).then(response=>{
          if (response.code==200){
            this.$message.success(response.msg);
            this.addAuthFormVisible =false
            this.toTree()
            return
          }
          this.$message.warning(response.msg);
        })
        console.log(this.authForm)
      })
    },
    addAuth(){
      this.title="添加菜单"
      this.addAuthFormVisible=true
    },
    // 编辑权限
    handleEdit(index, row) {
      this.title = "编辑菜单"
      this.addAuthFormVisible = true
        getonePermission(row.id).then(response=>{
          this.authForm = response.data.permission
          if (this.authForm.pid != 0) {
            this.label = response.data.parentTitle
            this.id = response.data.permission.pid
            return
          }
          // 目录 系统管理  回显上级菜单时  显示主目录
          this.label = '主目录'
          this.id = 0
          console.log(this.authForm)
        }).catch(erro=>{
          this.$message.error("请求失败!!")
        })
    },
    // 删除权限
    handleDelete(index, row) {
        deleteOne(row.id).then(res=>{
            if(res.code==200){
              this.$message.success(res.msg)
              this.toTree()
              return
            }
            this.$message.error(res.msg)
        }).catch(erro=>{
          this.$message.error("请求失败！！！")
        })
    },
    async toTree(){
      let {data} = await instance.get("/permission/list")
      this.tableData = listToTree(data)
      data = data.filter(dt => dt.isMenu != 2);
      let permissions = data.map(p => {
        return {
          label: p.title,
          id: p.id,
          pid: p.pid
        }
      })
      //permissions [{label:,id:,pid:}]
      let select = {
        label: '主目录',
        id: 0,
        children: [...listToTree(permissions)]
      }
      this.list = [select]
    }
  },
  created() {
    this.toTree()
  },
  watch:{
    'authForm.isMenu':{
      // handler是固定的配置选项，不能改变它的名称
      handler:function(newName, oldName){
        if(newName==0){
          this.authorityshow=false
          this.showcom=false
        }
        else if(newName==1){
          this.authorityshow=false
          this.showcom=true
        }
        else {
          this.authorityshow=true
          this.showcom=false
        }
      },
      deep:true//显式的改为true，表示要进行深度监听
    }
  }
}
</script>

<style scoped>
#search {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #eee;
}

#search, #header-bth {
  margin: 15px;
}

#auth-table {
  height: 100%;
}
</style>
